<template>
  <view class="container">
    <my-navbar-top></my-navbar-top>
    <view class="address">
      <!-- 表单 -->
      <view class="ef-form">
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">联系人</view>
          </view>
          <view class="ef-form__item-body">
            <uni-easyinput
              v-model="valiFormData.realname"
              primaryColor="#c9a063"
              :inputBorder="false"
              placeholder="请输入您的姓名"
            />
          </view>
        </view>
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">手机号</view>
          </view>
          <view class="ef-form__item-body">
            <uni-easyinput
              type="number"
              maxlength="11"
              v-model="valiFormData.telephone"
              :inputBorder="false"
              primaryColor="#c9a063"
              placeholder="请输入您的手机号"
            />
            <button
              open-type="getPhoneNumber"
              @getphonenumber="decryptPhoneNumber"
              class="auth-phone"
            >
              授权手机号
            </button>
          </view>
        </view>
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">省市区</view>
            <view @click="handleChooseAddress" class="auth-phone">
              授权微信地址
            </view>
          </view>
          <view
            class="ef-form__item-body address-picker"
            style="background: transparent; padding: 0"
          >
            <picker
              mode="region"
              @change="handlePickerChange"
              style="margin-right: 12rpx"
            >
              <view class="address-picker-item">
                <text v-if="valiFormData.province" style="color: #545454">{{
                  valiFormData.province || '省'
                }}</text>
                <text v-else style="color: #999">省</text>
                <image src="@/static/images/gray-right.png" mode="widthFix" />
              </view>
            </picker>

            <picker
              mode="region"
              @change="handlePickerChange"
              style="margin-right: 12rpx"
            >
              <view class="address-picker-item">
                <text v-if="valiFormData.city" style="color: #545454">{{
                  valiFormData.city || '市'
                }}</text>
                <text v-else style="color: #999">市</text>
                <image src="@/static/images/gray-right.png" mode="widthFix" />
              </view>
            </picker>
            <picker mode="region" @change="handlePickerChange">
              <view class="address-picker-item">
                <text v-if="valiFormData.area" style="color: #545454">{{
                  valiFormData.area || '区'
                }}</text>
                <text v-else style="color: #999">区</text>
                <image src="@/static/images/gray-right.png" mode="widthFix" />
              </view>
            </picker>
          </view>
        </view>

        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">详细地址</view>
          </view>
          <view class="ef-form__item-body">
            <uni-easyinput
              v-model="valiFormData.address"
              :inputBorder="false"
              primaryColor="#c9a063"
              placeholder="请填写详细地址"
            />
          </view>
        </view>
        <view class="ef-form__item">
          <view class="ef-form__item-header">
            <view class="title">设置为默认地址</view>
            <view class="switch">
              <switch
                :checked="valiFormData.is_default"
                @change="handleSwitchChange"
                style="transform: scale(0.8)"
                color="#c9a063"
              />
            </view>
          </view>
        </view>
      </view>

      <view class="address-add">
        <button class="secondary-button" @click="cancel">取消</button>
        <button class="primary-button" @click="save">保存地址</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'Address',
  data() {
    return {
      addressId: '',
      // 校验表单数据
      valiFormData: {
        user_address_id: '',
        realname: '',
        telephone: '',
        address: '',
        province: '',
        city: '',
        area: '',
        is_default: false,
      },
    }
  },
  onLoad(e) {
    if (e.id) {
      this.initData(e.id)
      this.addressId = e.id || ''
    }
  },
  methods: {
    initData(id) {
      this.$api.getAddressDetail({ user_address_id: id }).then((res) => {
        console.log(res)
        this.valiFormData = res.data.user_address
      })
    },
    handlePickerChange(e) {
      console.log(e)
      let { value, code } = e.detail
      this.valiFormData.province = value[0]
      this.valiFormData.city = value[1]
      this.valiFormData.area = value[2]
    },
    /**
     * 获取手机号
     */
    decryptPhoneNumber(e) {
      console.log(e)
      let { errMsg, code = null } = e.detail
      if (errMsg == 'getPhoneNumber:ok') {
        this.$api
          .decodePhone({
            code,
          })
          .then((res) => {
            console.log(res, '---')
            this.valiFormData.telephone = res.data.phoneNumber || ''
          })
      }
    },
    handleChooseAddress(e) {
      wx.chooseAddress({
        success: (res) => {
          console.log(res)
          this.valiFormData.realname = res.userName
          this.valiFormData.province = res.provinceName
          this.valiFormData.city = res.cityName
          this.valiFormData.area = res.countyName
          this.valiFormData.address = res.detailInfo
        },
        complete: (res) => {
          console.log(res, 'complete')
        },
      })
    },
    handleSwitchChange(e) {
      let { value } = e.detail
      console.log(value)
      this.valiFormData.is_default = value
      console.log(this.valiFormData)
    },
    cancel() {
      uni.navigateBack()
    },
    /**
     * 表单校验
     */
    formValidate() {
      return new Promise((resolve, reject) => {
        let { realname, telephone, address, province, city, area } =
          this.valiFormData
        if (!realname) {
          uni.showToast({
            title: '请输入姓名',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!telephone) {
          uni.showToast({
            title: '请输入手机号',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!address) {
          uni.showToast({
            title: '请输入地址',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!province) {
          uni.showToast({
            title: '请选择省',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!city) {
          uni.showToast({
            title: '请选择市',
            icon: 'none',
          })
          resolve(false)
          return
        }
        if (!area) {
          uni.showToast({
            title: '请选择区',
            icon: 'none',
          })
          resolve(false)
          return
        }

        resolve(true)
      })
    },
    save() {
      this.formValidate().then((res) => {
        console.log(res)
        if (!res) return
        let params = {
          ...this.valiFormData,
          is_default: this.valiFormData.is_default ? 1 : 0,
        }
        if (this.addressId) {
          params.user_address_id = this.addressId
          this.$api.updateAddress(params).then((res) => {
            console.log(res)
            if (res.code == 0) {
              this.handleToast('修改成功')
            }
          })
        } else {
          delete params.user_address_id
          this.$api.addAddress(params).then((res) => {
            if (res.code == 0) {
              this.handleToast('添加成功')
            }
          })
        }
      })
    },
    handleToast(title) {
      uni.showToast({
        title,
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    },
  },
}
</script>

<style lang="scss" scoped>
.address {
  width: 100%;
  padding: 50rpx 36rpx 154rpx 36rpx;
  overflow-y: auto;
  box-sizing: border-box;

  .address-add {
    width: 100%;
    background-color: #e7e7e7;
    border-radius: 2rpx;
    padding: 30rpx 33rpx;
    padding-bottom: calc(env(safe-area-inset-bottom) + 30rpx);
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    box-sizing: border-box;
    box-shadow: 0rpx -2rpx 10rpx 0rpx rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
  }

  .switch {
    margin-left: 20rpx;
  }

  .auth-phone {
    font-size: 24rpx;
    margin-left: 20rpx;
    line-height: 32rpx;
    color: var(--main-color);
    border-bottom: 2rpx solid var(--main-color);
  }
}
.address-picker {
  display: flex;
  align-items: center;
  width: 100%;
  picker {
    width: calc(100% / 3);
  }
  .address-picker-item {
    display: flex;
    font-size: 24rpx;
    color: #999;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    background-color: #fff;
    border-radius: 2rpx;
    padding: 0 20rpx;
    box-sizing: border-box;
    image {
      width: 20rpx;
      height: 20rpx;
    }
  }
}
</style>
